home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Browsers, Managers & Extensions / Mozilla Weave 0.2.7 / latest-weave.xpi / modules / engines.js < prev    next >
Text File  |  2008-09-19  |  19KB  |  560 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is Bookmarks Sync.
  15.  *
  16.  * The Initial Developer of the Original Code is Mozilla.
  17.  * Portions created by the Initial Developer are Copyright (C) 2007
  18.  * the Initial Developer. All Rights Reserved.
  19.  *
  20.  * Contributor(s):
  21.  *  Dan Mills <thunder@mozilla.com>
  22.  *  Myk Melez <myk@mozilla.org>
  23.  *
  24.  * Alternatively, the contents of this file may be used under the terms of
  25.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  26.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27.  * in which case the provisions of the GPL or the LGPL are applicable instead
  28.  * of those above. If you wish to allow use of your version of this file only
  29.  * under the terms of either the GPL or the LGPL, and not to allow others to
  30.  * use your version of this file under the terms of the MPL, indicate your
  31.  * decision by deleting the provisions above and replace them with the notice
  32.  * and other provisions required by the GPL or the LGPL. If you do not delete
  33.  * the provisions above, a recipient may use your version of this file under
  34.  * the terms of any one of the MPL, the GPL or the LGPL.
  35.  *
  36.  * ***** END LICENSE BLOCK ***** */
  37.  
  38. const EXPORTED_SYMBOLS = ['Engines', 'Engine', 'SyncEngine', 'BlobEngine'];
  39.  
  40. const Cc = Components.classes;
  41. const Ci = Components.interfaces;
  42. const Cr = Components.results;
  43. const Cu = Components.utils;
  44.  
  45. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  46. Cu.import("resource://weave/log4moz.js");
  47. Cu.import("resource://weave/constants.js");
  48. Cu.import("resource://weave/util.js");
  49. Cu.import("resource://weave/wrap.js");
  50. Cu.import("resource://weave/crypto.js");
  51. Cu.import("resource://weave/dav.js");
  52. Cu.import("resource://weave/remote.js");
  53. Cu.import("resource://weave/clientData.js");
  54. Cu.import("resource://weave/identity.js");
  55. Cu.import("resource://weave/stores.js");
  56. Cu.import("resource://weave/syncCores.js");
  57. Cu.import("resource://weave/trackers.js");
  58. Cu.import("resource://weave/async.js");
  59.  
  60. Function.prototype.async = Async.sugar;
  61.  
  62. // Singleton service, holds registered engines
  63.  
  64. Utils.lazy(this, 'Engines', EngineManagerSvc);
  65.  
  66. function EngineManagerSvc() {
  67.   this._engines = {};
  68. }
  69. EngineManagerSvc.prototype = {
  70.   get: function EngMgr_get(name) {
  71.     return this._engines[name];
  72.   },
  73.   getAll: function EngMgr_getAll() {
  74.     let ret = [];
  75.     for (key in this._engines) {
  76.       ret.push(this._engines[key]);
  77.     }
  78.     return ret;
  79.   },
  80.   getEnabled: function EngMgr_getEnabled() {
  81.     let ret = [];
  82.     for (key in this._engines) {
  83.       if(this._engines[key].enabled)
  84.         ret.push(this._engines[key]);
  85.     }
  86.     return ret;
  87.   },
  88.   register: function EngMgr_register(engine) {
  89.     this._engines[engine.name] = engine;
  90.   },
  91.   unregister: function EngMgr_unregister(val) {
  92.     let name = val;
  93.     if (val instanceof Engine)
  94.       name = val.name;
  95.     delete this._engines[name];
  96.   }
  97. };
  98.  
  99. function Engine() {}
  100. Engine.prototype = {
  101.   _notify: Wrap.notify,
  102.  
  103.   // "default-engine";
  104.   get name() { throw "name property must be overridden in subclasses"; },
  105.  
  106.   // "Default";
  107.   get displayName() { throw "displayName property must be overriden in subclasses"; },
  108.  
  109.   // "DefaultEngine";
  110.   get logName() { throw "logName property must be overridden in subclasses"; },
  111.  
  112.   // "user-data/default-engine/";
  113.   get serverPrefix() { throw "serverPrefix property must be overridden in subclasses"; },
  114.  
  115.   get _remote() {
  116.     let remote = new RemoteStore(this);
  117.     this.__defineGetter__("_remote", function() remote);
  118.     return remote;
  119.   },
  120.  
  121.   get enabled() {
  122.     return Utils.prefs.getBoolPref("engine." + this.name);
  123.   },
  124.  
  125.   get _os() {
  126.     let os = Cc["@mozilla.org/observer-service;1"].
  127.       getService(Ci.nsIObserverService);
  128.     this.__defineGetter__("_os", function() os);
  129.     return os;
  130.   },
  131.  
  132.   get _json() {
  133.     let json = Cc["@mozilla.org/dom/json;1"].
  134.       createInstance(Ci.nsIJSON);
  135.     this.__defineGetter__("_json", function() json);
  136.     return json;
  137.   },
  138.  
  139.   // _core, _store and _tracker need to be overridden in subclasses
  140.   get _store() {
  141.     let store = new Store();
  142.     this.__defineGetter__("_store", function() store);
  143.     return store;
  144.   },
  145.  
  146.   get _core() {
  147.     let core = new SyncCore(this._store);
  148.     this.__defineGetter__("_core", function() core);
  149.     return core;
  150.   },
  151.  
  152.   get _tracker() {
  153.     let tracker = new tracker();
  154.     this.__defineGetter__("_tracker", function() tracker);
  155.     return tracker;
  156.   },
  157.  
  158.   get engineId() {
  159.     let id = ID.get('Engine:' + this.name);
  160.     if (!id) {
  161.       // Copy the service login from WeaveID
  162.       let masterID = ID.get('WeaveID');
  163.  
  164.       id = new Identity(this.logName, masterID.username, masterID.password);
  165.       ID.set('Engine:' + this.name, id);
  166.     }
  167.     return id;
  168.   },
  169.  
  170.   _init: function Engine__init() {
  171.     let levelPref = "log.logger.service.engine." + this.name;
  172.     let level = "Debug";
  173.     try { level = Utils.prefs.getCharPref(levelPref); }
  174.     catch (e) { /* ignore unset prefs */ }
  175.  
  176.     this._log = Log4Moz.Service.getLogger("Service." + this.logName);
  177.     this._log.level = Log4Moz.Level[level];
  178.     this._osPrefix = "weave:" + this.name + ":";
  179.   },
  180.  
  181.   _serializeCommands: function Engine__serializeCommands(commands) {
  182.     let json = this._json.encode(commands);
  183.     //json = json.replace(/ {action/g, "\n {action");
  184.     return json;
  185.   },
  186.  
  187.   _serializeConflicts: function Engine__serializeConflicts(conflicts) {
  188.     let json = this._json.encode(conflicts);
  189.     //json = json.replace(/ {action/g, "\n {action");
  190.     return json;
  191.   },
  192.  
  193.   _resetServer: function Engine__resetServer() {
  194.     let self = yield;
  195.     yield this._remote.wipe(self.cb);
  196.   },
  197.  
  198.   _resetClient: function Engine__resetClient() {
  199.     let self = yield;
  200.     this._log.debug("Resetting client state");
  201.     this._store.wipe();
  202.     this._log.debug("Client reset completed successfully");
  203.   },
  204.  
  205.   _sync: function Engine__sync() {
  206.     let self = yield;
  207.     throw "_sync needs to be subclassed";
  208.   },
  209.  
  210.   _initialUpload: function Engine__initialUpload() {
  211.     let self = yield;
  212.     throw "_initialUpload needs to be subclassed";
  213.   },
  214.  
  215.   _share: function Engine__share(guid, username) {
  216.     let self = yield;
  217.     /* This should be overridden by the engine subclass for each datatype.
  218.        Implementation should share the data node identified by guid,
  219.        and all its children, if any, with the user identified by username. */
  220.     self.done();
  221.   },
  222.  
  223.   _stopSharing: function Engine__stopSharing(guid, username) {
  224.     let self = yield;
  225.     /* This should be overridden by the engine subclass for each datatype.
  226.      Stop sharing the data node identified by guid with the user identified
  227.      by username.*/
  228.     self.done();
  229.   },
  230.  
  231.   sync: function Engine_sync(onComplete) {
  232.     return this._sync.async(this, onComplete);
  233.   },
  234.  
  235.   share: function Engine_share(onComplete, guid, username) {
  236.     return this._share.async(this, onComplete, guid, username);
  237.   },
  238.  
  239.   stopSharing: function Engine_share(onComplete, guid, username) {
  240.     return this._stopSharing.async(this, onComplete, guid, username);
  241.   },
  242.  
  243.   resetServer: function Engimne_resetServer(onComplete) {
  244.     this._notify("reset-server", "", this._resetServer).async(this, onComplete);
  245.   },
  246.  
  247.   resetClient: function Engine_resetClient(onComplete) {
  248.     this._notify("reset-client", "", this._resetClient).async(this, onComplete);
  249.   }
  250. };
  251.  
  252. function SyncEngine() {}
  253. SyncEngine.prototype = {
  254.   __proto__: new Engine(),
  255.  
  256.   get _snapshot() {
  257.     let snap = new SnapshotStore(this.name);
  258.     this.__defineGetter__("_snapshot", function() snap);
  259.     return snap;
  260.   },
  261.  
  262.   _resetClient: function SyncEngine__resetClient() {
  263.     let self = yield;
  264.     this._log.debug("Resetting client state");
  265.     this._snapshot.wipe();
  266.     this._store.wipe();
  267.     this._log.debug("Client reset completed successfully");
  268.   },
  269.  
  270.   _initialUpload: function Engine__initialUpload() {
  271.     let self = yield;
  272.     this._log.info("Initial upload to server");
  273.     this._snapshot.data = this._store.wrap();
  274.     this._snapshot.version = 0;
  275.     this._snapshot.GUID = null; // in case there are other snapshots out there
  276.     yield this._remote.initialize(self.cb, this._snapshot);
  277.     this._snapshot.save();
  278.   },
  279.  
  280.   //       original
  281.   //         / \
  282.   //      A /   \ B
  283.   //       /     \
  284.   // client --C-> server
  285.   //       \     /
  286.   //      D \   / C
  287.   //         \ /
  288.   //        final
  289.  
  290.   // If we have a saved snapshot, original == snapshot.  Otherwise,
  291.   // it's the empty set {}.
  292.  
  293.   // C is really the diff between server -> final, so if we determine
  294.   // D we can calculate C from that.  In the case where A and B have
  295.   // no conflicts, C == A and D == B.
  296.  
  297.   // Sync flow:
  298.   // 1) Fetch server deltas
  299.   // 1.1) Construct current server status from snapshot + server deltas
  300.   // 1.2) Generate single delta from snapshot -> current server status ("B")
  301.   // 2) Generate local deltas from snapshot -> current client status ("A")
  302.   // 3) Reconcile client/server deltas and generate new deltas for them.
  303.   //    Reconciliation won't generate C directly, we will simply diff
  304.   //    server->final after step 3.1.
  305.   // 3.1) Apply local delta with server changes ("D")
  306.   // 3.2) Append server delta to the delta file and upload ("C")
  307.  
  308.   _sync: function SyncEngine__sync() {
  309.     let self = yield;
  310.  
  311.     this._log.info("Beginning sync");
  312.     this._os.notifyObservers(null, "weave:service:sync:engine:start", this.displayName);
  313.  
  314.     this._snapshot.load();
  315.  
  316.     try {
  317.       this._remote.status.data; // FIXME - otherwise we get an error...
  318.       yield this._remote.openSession(self.cb, this._snapshot);
  319.  
  320.     } catch (e if e.status == 404) {
  321.       yield this._initialUpload.async(this, self.cb);
  322.       return;
  323.     }
  324.  
  325.     // 1) Fetch server deltas
  326.  
  327.     this._os.notifyObservers(null, "weave:service:sync:status", "status.downloading-deltas");
  328.     let serverSnap = yield this._remote.wrap(self.cb);
  329.     let serverUpdates = yield this._core.detectUpdates(self.cb,
  330.                                                        this._snapshot.data, serverSnap);
  331.  
  332.     // 2) Generate local deltas from snapshot -> current client status
  333.  
  334.     this._os.notifyObservers(null, "weave:service:sync:status", "status.calculating-differences");
  335.     let localSnap = new SnapshotStore();
  336.     localSnap.data = this._store.wrap();
  337.     this._core.detectUpdates(self.cb, this._snapshot.data, localSnap.data);
  338.     let localUpdates = yield;
  339.  
  340.     this._log.trace("local json:\n" + localSnap.serialize());
  341.     this._log.trace("Local updates: " + this._serializeCommands(localUpdates));
  342.     this._log.trace("Server updates: " + this._serializeCommands(serverUpdates));
  343.  
  344.     if (serverUpdates.length == 0 && localUpdates.length == 0) {
  345.       this._os.notifyObservers(null, "weave:service:sync:status", "status.no-changes-required");
  346.       this._log.info("Sync complete: no changes needed on client or server");
  347.       this._snapshot.version = this._remote.status.data.maxVersion;
  348.       this._snapshot.save();
  349.       self.done(true);
  350.       return;
  351.     }
  352.  
  353.     // 3) Reconcile client/server deltas and generate new deltas for them.
  354.  
  355.     this._os.notifyObservers(null, "weave:service:sync:status", "status.reconciling-updates");
  356.     this._log.info("Reconciling client/server updates");
  357.     let ret = yield this._core.reconcile(self.cb, localUpdates, serverUpdates);
  358.  
  359.     let clientChanges = ret.propagations[0];
  360.     let serverChanges = ret.propagations[1];
  361.     let clientConflicts = ret.conflicts[0];
  362.     let serverConflicts = ret.conflicts[1];
  363.  
  364.     this._log.info("Changes for client: " + clientChanges.length);
  365.     this._log.info("Predicted changes for server: " + serverChanges.length);
  366.     this._log.info("Client conflicts: " + clientConflicts.length);
  367.     this._log.info("Server conflicts: " + serverConflicts.length);
  368.     this._log.trace("Changes for client: " + this._serializeCommands(clientChanges));
  369.     this._log.trace("Predicted changes for server: " + this._serializeCommands(serverChanges));
  370.     this._log.trace("Client conflicts: " + this._serializeConflicts(clientConflicts));
  371.     this._log.trace("Server conflicts: " + this._serializeConflicts(serverConflicts));
  372.  
  373.     if (!(clientChanges.length || serverChanges.length ||
  374.           clientConflicts.length || serverConflicts.length)) {
  375.       this._os.notifyObservers(null, "weave:service:sync:status", "status.no-changes-required");
  376.       this._log.info("Sync complete: no changes needed on client or server");
  377.       this._snapshot.data = localSnap.data;
  378.       this._snapshot.version = this._remote.status.data.maxVersion;
  379.       this._snapshot.save();
  380.       self.done(true);
  381.       return;
  382.     }
  383.  
  384.     if (clientConflicts.length || serverConflicts.length)
  385.       this._log.warn("Conflicts found!  Discarding server changes");
  386.  
  387.     // 3.1) Apply server changes to local store
  388.  
  389.     if (clientChanges.length) {
  390.       this._log.info("Applying changes locally");
  391.       this._os.notifyObservers(null, "weave:service:sync:status", "status.applying-changes");
  392.  
  393.       // apply to real store
  394.       yield this._store.applyCommands.async(this._store, self.cb, clientChanges);
  395.  
  396.       // get the current state
  397.       let newSnap = new SnapshotStore();
  398.       newSnap.data = this._store.wrap();
  399.  
  400.       // apply to the snapshot we got in step 1, and compare with current state
  401.       yield localSnap.applyCommands.async(localSnap, self.cb, clientChanges);
  402.       let diff = yield this._core.detectUpdates(self.cb,
  403.                                                 localSnap.data, newSnap.data);
  404.       if (diff.length != 0) {
  405.         this._log.warn("Commands did not apply correctly");
  406.         this._log.trace("Diff from snapshot+commands -> " +
  407.                         "new snapshot after commands:\n" +
  408.                         this._serializeCommands(diff));
  409.       }
  410.  
  411.       // update the local snap to the current state, we'll use it below
  412.       localSnap.data = newSnap.data;
  413.       localSnap.version = this._remote.status.data.maxVersion;
  414.     }
  415.  
  416.     // 3.2) Append server delta to the delta file and upload
  417.  
  418.     // Generate a new diff, from the current server snapshot to the
  419.     // current client snapshot.  In the case where there are no
  420.     // conflicts, it should be the same as what the resolver returned
  421.  
  422.     this._os.notifyObservers(null, "weave:service:sync:status",
  423.                              "status.calculating-differences");
  424.     let serverDelta = yield this._core.detectUpdates(self.cb,
  425.                                                      serverSnap, localSnap.data);
  426.  
  427.     // Log an error if not the same
  428.     if (!(serverConflicts.length ||
  429.           Utils.deepEquals(serverChanges, serverDelta)))
  430.       this._log.warn("Predicted server changes differ from " +
  431.                      "actual server->client diff (can be ignored in many cases)");
  432.  
  433.     this._log.info("Actual changes for server: " + serverDelta.length);
  434.     this._log.trace("Actual changes for server: " +
  435.                     this._serializeCommands(serverDelta));
  436.  
  437.     if (serverDelta.length) {
  438.       this._log.info("Uploading changes to server");
  439.       this._os.notifyObservers(null, "weave:service:sync:status",
  440.                                "status.uploading-deltas");
  441.  
  442.       yield this._remote.appendDelta(self.cb, localSnap, serverDelta,
  443.                                      {maxVersion: this._snapshot.version,
  444.                                       deltasEncryption: Crypto.defaultAlgorithm});
  445.       localSnap.version = this._remote.status.data.maxVersion;
  446.  
  447.       this._log.info("Successfully updated deltas and status on server");
  448.     }
  449.  
  450.     this._snapshot.data = localSnap.data;
  451.     this._snapshot.version = localSnap.version;
  452.     this._snapshot.save();
  453.  
  454.     this._log.info("Sync complete");
  455.     self.done(true);
  456.   }
  457. };
  458.  
  459. function BlobEngine() {
  460.   // subclasses should call _init
  461.   // we don't call it here because it requires serverPrefix to be set
  462. }
  463. BlobEngine.prototype = {
  464.   __proto__: new Engine(),
  465.  
  466.   get _profileID() {
  467.     return ClientData.GUID;
  468.   },
  469.  
  470.   _init: function BlobEngine__init() {
  471.     // FIXME meep?
  472.     this.__proto__.__proto__.__proto__.__proto__._init.call(this);
  473.     this._keys = new Keychain(this.serverPrefix);
  474.     this._file = new Resource(this.serverPrefix + "data");
  475.     this._file.pushFilter(new JsonFilter());
  476.     this._file.pushFilter(new CryptoFilter(this.engineId));
  477.   },
  478.  
  479.   _initialUpload: function BlobEngine__initialUpload() {
  480.     let self = yield;
  481.     this._log.info("Initial upload to server");
  482.     yield this._keys.initialize(self.cb, this.engineId);
  483.     this._file.data = {};
  484.     yield this._merge.async(this, self.cb);
  485.     yield this._file.put(self.cb);
  486.   },
  487.  
  488.   // NOTE: Assumes this._file has latest server data
  489.   // this method is separate from _sync so it's easy to override in subclasses
  490.   _merge: function BlobEngine__merge() {
  491.     let self = yield;
  492.     this._file.data[this._profileID] = this._store.wrap();
  493.   },
  494.  
  495.   // This engine is very simple:
  496.   // 1) Get the latest server data
  497.   // 2) Merge with our local data store
  498.   // 3) Upload new merged data
  499.   // NOTE: a version file will be needed in the future to optimize the case
  500.   //       where there are no changes
  501.   _sync: function BlobEngine__sync() {
  502.     let self = yield;
  503.  
  504.     this._log.info("Beginning sync");
  505.     this._os.notifyObservers(null, "weave:service:sync:engine:start", this.name);
  506.  
  507.     if (!(yield DAV.MKCOL(this.serverPrefix, self.cb)))
  508.       throw "Could not create remote folder";
  509.  
  510.     try {
  511.       if ("none" != Utils.prefs.getCharPref("encryption"))
  512.         yield this._keys.getKeyAndIV(self.cb, this.engineId);
  513.       yield this._file.get(self.cb);
  514.       yield this._merge.async(this, self.cb);
  515.       yield this._file.put(self.cb);
  516.  
  517.     } catch (e if e.status == 404) {
  518.       yield this._initialUpload.async(this, self.cb);
  519.     }
  520.  
  521.     this._log.info("Sync complete");
  522.     this._os.notifyObservers(null, "weave:service:sync:engine:success", this.name);
  523.     self.done(true);
  524.   }
  525. };
  526.  
  527. function HeuristicEngine() {
  528. }
  529. HeuristicEngine.prototype = {
  530.   __proto__: new Engine(),
  531.  
  532.   get _snapshot() {
  533.     let snap = new SnapshotStore(this.name);
  534.     this.__defineGetter__("_snapshot", function() snap);
  535.     return snap;
  536.   },
  537.  
  538.   _resetClient: function SyncEngine__resetClient() {
  539.     let self = yield;
  540.     this._log.debug("Resetting client state");
  541.     this._snapshot.wipe();
  542.     this._store.wipe();
  543.     this._log.debug("Client reset completed successfully");
  544.   },
  545.  
  546.   _initialUpload: function HeuristicEngine__initialUpload() {
  547.     let self = yield;
  548.     this._log.info("Initial upload to server");
  549.     this._snapshot.data = this._store.wrap();
  550.     this._snapshot.version = 0;
  551.     this._snapshot.GUID = null; // in case there are other snapshots out there
  552.     yield this._remote.initialize(self.cb, this._snapshot);
  553.     this._snapshot.save();
  554.   },
  555.  
  556.   _sync: function HeuristicEngine__sync() {
  557.     let self = yield;
  558.   }
  559. };
  560.